package com.example.shuiyin.config;

import org.flywaydb.core.Flyway;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.net.InetSocketAddress;
import java.net.Socket;

@Configuration
@Slf4j
public class FlywayConfig {

    @Bean
    public Flyway flyway() {
        log.info("初始化Flyway配置...");
        
        // 添加环境变量或系统属性检查，允许跳过Flyway
        String skipFlyway = System.getProperty("skipFlyway", "true"); // 默认为true，跳过迁移
        if (Boolean.parseBoolean(skipFlyway)) {
            log.info("跳过Flyway迁移，由于skipFlyway=true");
            return Flyway.configure()
                    .locations("classpath:db/migration")
                    .baselineOnMigrate(true)
                    .load();
        }
        
        // 检查MySQL服务是否可用
        if (!isMysqlRunning("localhost", 3306)) {
            log.error("MySQL服务未运行，Flyway将不会执行迁移");
            // 返回一个不会执行migrate的Flyway实例
            return Flyway.configure()
                    .locations("classpath:db/migration")
                    .baselineOnMigrate(true)
                    .load();
        }
        
        try {
            log.info("使用直接配置数据源连接Flyway");
            
            // 创建硬编码的DataSource避免依赖占位符解析
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setUrl("jdbc:mysql://localhost:3306/shuiyin?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true&useSSL=false");
            dataSource.setUsername("shuiyin");
            dataSource.setPassword("8888");
            dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
            
            Flyway flyway = Flyway.configure()
                    .dataSource(dataSource)
                    .locations("classpath:db/migration")
                    .baselineOnMigrate(true)
                    .load();
                    
            log.info("Flyway配置完成，使用直接配置的数据源");
            return flyway;
        } catch (Exception e) {
            log.error("Flyway配置失败: {}", e.getMessage(), e);
            // 创建一个空的Flyway实例，避免应用启动失败
            return Flyway.configure()
                    .locations("classpath:db/migration")
                    .baselineOnMigrate(true)
                    .load();
        }
    }
    
    private boolean isMysqlRunning(String host, int port) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(host, port), 1000);
            log.info("MySQL服务检测：运行中 ({}:{})", host, port);
            return true;
        } catch (Exception e) {
            log.error("MySQL服务检测：未运行 ({}:{})", host, port);
            return false;
        }
    }
} 